package com.jty.lib_base.whiteboard

import android.content.Context
import android.util.Log
import com.jty.lib_base.R
import okhttp3.*
import java.io.*
import java.util.zip.ZipEntry
import java.util.zip.ZipInputStream


/**
 * author: zhouyh
 * created on: 2022/3/16 2:52 下午
 * description:声网白板配置
 */
class WhiteboardApi {
    var sdkToken:String?=null
    var appId:String?=null
    var appIdentifier:String?=null
    var roomUUID:String?=null
    var roomToken:String?=null

    fun init(context:Context){
        appId = context.getString(R.string.sdk_app_id)
        sdkToken = context.getString(R.string.sdk_app_token)
        roomUUID = context.getString(R.string.room_uuid)
        roomToken = context.getString(R.string.room_token)
        appIdentifier = context.getString(R.string.sdk_app_identifier)
    }

    //是否配置白板信息
    fun hasWhiteBoardInfo():Boolean{
        return roomUUID!!.isNotEmpty() && roomToken!!.isNotEmpty()
    }

    //token是否有效
    fun invalidToken():Boolean{
        return !hasWhiteBoardInfo() && sdkToken!!.length<=50
    }

    interface Result{
        fun success(uuid:String?,token:String?)
        fun fail(message:String?)
    }


    fun getNewRoom(result:Result){
        if (hasWhiteBoardInfo()){
            result.success(roomUUID,roomToken)
            return
        }

        WhiteboardApiService.createRoom(sdkToken,100,"cn-hz",object:
            WhiteboardCallback<CreateRoomResult> {
            override fun onSuccess(data: CreateRoomResult) {
                roomUUID = data.uuid
                getRoomToken(data.uuid,result) }

            override fun onFailure(message: String?) {
                result.fail(message)
            }
        })
    }

    fun getRoomToken(uuid:String,result:Result){
        if (uuid == roomUUID && hasWhiteBoardInfo()){
            result.success(roomUUID,roomToken)
            return
        }
        WhiteboardApiService.createRoomToken(sdkToken,uuid,"cn-hz",object:
            WhiteboardCallback<String> {
            override fun onSuccess(token: String?) {
                roomToken = token
                result.success(uuid,token)
            }

            override fun onFailure(message: String?) {
                result.fail(message)
            }
        })
    }

    private val client = OkHttpClient()
    fun downloadZip(zipUrl:String?,des:String){
        val request = Request.Builder().url(zipUrl).build()
        val call = client.newCall(request)
        call.enqueue(object : Callback{
            override fun onFailure(call: Call, e: IOException) {
                Log.e(TAG, "download error: $e")
            }

            override fun onResponse(call: Call, response: Response) {
                if (!response.isSuccessful) {
                    throw IOException("下载失败: $response")
                }
                val path = "$des/convertcdn.netless.link/dynamicConvert"
                val file = File(path)
                if (!file.exists()) {
                    val success = file.mkdirs()
                    Log.i("LocalFile", "success: $success path: $path")
                } else {
                    Log.i("LocalFile", "$path is exist")
                }
                val fos = FileOutputStream("$path/1.zip", false)
                fos.write(response.body()!!.bytes())
                fos.close()
                unzip(File("$path/1.zip"), File(path))
                Log.i("LocalFile", "unzip")
            }

        })
    }

    //伴生对象相当于单例
    companion object{
        private const val TAG = "WhiteboardApi"
        const val DEFAULT_UID = "5e62a5c0-8c15-4b00-a9fc-0e309e91da30"
        private var instance:WhiteboardApi?=null

        fun get():WhiteboardApi?{
            if (instance==null){
                instance = WhiteboardApi()
            }
            return instance
        }

        private fun unzip(zipFile:File,targetDirectory:File){
            ZipInputStream(BufferedInputStream(FileInputStream(zipFile))).use { zis ->
                var ze : ZipEntry
                while (zis.nextEntry.also { ze = it }!=null){
                    val file = File(targetDirectory,ze.name)
                    val dir = if (ze.isDirectory)file else file.parentFile
                    if (!dir.isDirectory && !dir.mkdirs())throw FileNotFoundException("Failed to ensure directory:" + dir.absolutePath)
                    if (ze.isDirectory)continue
                    FileOutputStream(file).use { fos ->
                        var count : Int
                        val buffer = ByteArray(8192)
                        while (zis.read(buffer).also {
                                count=it }!=-1)fos.write(buffer,0,count)
                    }
                }
            }
        }



    }


}